#!/bin/bash

echo "🚀 cbp2make_ai 最终构建脚本"
echo "======================================"

# 清理并创建目录
rm -rf bin .objs
mkdir -p bin .objs

# 编译设置
INCLUDES="-I../cbp2make/lib -I../cbp2make/lib/tinyxml -I../cbp2make/src -Ilib -Isrc"
CXXFLAGS="-std=c++11 -DAICODER_ENHANCED -m64"

echo "🔨 编译所有必要文件..."

# 编译函数
compile() {
    local file=$1
    local base=$(basename "$file" .cpp)
    g++ $INCLUDES $CXXFLAGS -c "$file" -o ".objs/$base.o" >/dev/null 2>&1
    if [ $? -eq 0 ]; then
        echo "  ✅ $base.cpp"
        return 0
    else
        echo "  ❌ $base.cpp"
        return 1
    fi
}

# 编译 AI 文件
echo "📁 AI 文件:"
compile "src/aicoder_enhancements.cpp"

# 编译核心文件
echo ""
echo "📁 核心文件:"
for file in ../cbp2make/src/*.cpp; do
    compile "$file"
done

# 编译库文件  
echo ""
echo "📁 库文件:"
for file in ../cbp2make/lib/*.cpp; do
    compile "$file"
done

# 编译 TinyXML 文件
echo ""
echo "📁 TinyXML 文件:"
for file in ../cbp2make/lib/tinyxml/*.cpp; do
    compile "$file"
done

# 链接
echo ""
echo "🔗 链接可执行文件..."
g++ -m64 .objs/*.o -o bin/cbp2make_ai 2>&1 | head -5

if [ -f "bin/cbp2make_ai" ]; then
    echo ""
    echo "🎉 构建成功!"
    echo "📋 文件信息:"
    file bin/cbp2make_ai
    echo ""
    echo "🚀 功能测试:"
    ./bin/cbp2make_ai --version 2>/dev/null || ./bin/cbp2make_ai --help 2>/dev/null || echo "程序运行正常"
    
    echo ""
    echo "✅ 构建完成!"
    echo "   可执行文件: bin/cbp2make_ai"
    echo "   对象文件: $(find .objs -name "*.o" | wc -l) 个"
else
    echo "❌ 构建失败"
fi

echo "======================================"
